package fm.yichenet.mongo.service.impl;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import fm.dao.HibernateBaseDao;
import fm.dao.MongoBaseDao;
import fm.dao.SolrBaseDao;
import fm.entity.OrderGood;
import fm.dto.NeiyiUser;
import fm.entityEnum.CarouselType;
import fm.entityEnum.CollectTypeEnum;
import fm.entityEnum.OrderEnum;
import fm.exception.BizException;
import fm.mongo.MCondition;
import fm.mongo.MRel;
import fm.mongo.MongoTable;
import fm.util.CommonUtils;
import fm.web.CurrentRequest;
import fm.yichenet.mongo.service.ExpressService;
import fm.yichenet.mongo.service.GoodMgrService;
import fm.yichenet.service.OrderService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.sql.Timestamp;
import java.util.*;

/**
 * 文件描述：
 * 更新时间：2017/4/3
 * 更新人： codingmates@gmail.com .
 */
@Service
public class GoodMgrServiceImpl implements GoodMgrService {
    @Autowired
    private MongoBaseDao mongoBaseDao;

    @Autowired
    OrderService orderService;

    @Autowired
    ExpressService expressService;
    @Override
    public List<DBObject> getList(Map param, Integer pageNum, Integer pageSize, DBObject sort) throws Exception {
        if (pageNum != null && pageSize != null) {
            return (List<DBObject>) mongoBaseDao.getPageList(param, DBObject.class, pageSize, pageNum, MongoTable.good, sort);
        } else {
            return (List<DBObject>) mongoBaseDao.getList(param, DBObject.class, MongoTable.good, sort);
        }
    }

    @Override
    public long countAll(Map param) throws Exception {
        return mongoBaseDao.count(param, MongoTable.good);
    }

    @Override
    public void addGood(Map param) throws Exception {
        if (CommonUtils.isEmpty(param.get("good_express"))) {
            throw new BizException("请为商品选择物流信息！");
        }
        param.remove("goodExpress");//多余数据
        Object priority = param.get("priority");
        Object sourcePrice = param.get("source_price");
        Object salePrice = param.get("sale_price");
        Object unprice = param.get("unprice");
        if(Integer.parseInt((String) unprice)==1){
            sourcePrice=0;
            salePrice=0;
            param.put("source_price", sourcePrice);
            param.put("salePrice", salePrice);
        }
        if (sourcePrice != null) {
            try {
                if (sourcePrice instanceof String) {
                    param.put("source_price", Integer.parseInt((String) sourcePrice));
                }
            } catch (Exception ex) {
                throw new BizException("商品的原价只能为数字，请勿输入其他字符！");
            }
        }



        if (sourcePrice != null) {
            try {
                if (sourcePrice instanceof String) {
                    param.put("sale_price", Integer.parseInt((String) salePrice));
                }
            } catch (Exception ex) {
                throw new BizException("商品的售价只能为数字，请勿输入其他字符！");
            }
        }

        if (CommonUtils.isEmpty(priority)) {
            param.put("priority", 0);
        } else if (priority instanceof String) {
            param.put("priority", Integer.parseInt((String) priority));
        } else {
            param.put("priority", 0);
        }
        param.put("status", "1");
        param.put("latm", new Date());
//        param.put("colorPrices",)
        mongoBaseDao.insert(param, MongoTable.good);
    }

    @Override
    public void updateGood(Map param) throws Exception {
        Map query = new HashMap();
        if (param.containsKey("shop_id")) {
            query.put("shop_id", param.get("shop_id"));
        }
        query.put("good_id", param.get("good_id"));

        DBObject good = (DBObject) mongoBaseDao.findOne(query, DBObject.class, MongoTable.good);
        if (good == null) {
            throw new RuntimeException("未找到对应的商品信息，修改失败");
        }
        if (param.containsKey("img")) {
            List<String> imgs = (List<String>) good.get("img");
            if (!CollectionUtils.isNotEmpty(imgs)) {
                imgs = new ArrayList<>();
            }
            List<String> newImgs = new ArrayList<>();
            for (String img : imgs) {
                if (StringUtils.isNotEmpty(img) && (img.indexOf((String) param.get("src")) == -1 ||
                        ((String) param.get("src")).indexOf("emptyImg.png") != -1)) {
                    newImgs.add(img);
                }
            }
            newImgs.add((String) param.get("img"));
            good.put("img", newImgs);
        } else {
            good.putAll(param);
        }
        if (param.containsKey("priority")) {
            Object priority = good.get("priority");
            if (CommonUtils.isEmpty(priority)) {
                good.put("priority", 0);
            } else if (priority instanceof String) {
                good.put("priority", Integer.parseInt((String) priority));
            } else {
                good.put("priority", 0);
            }
        }

        mongoBaseDao.updateOne(query, good.toMap(), MongoTable.good);
    }

    @Override
    public void delGood(Map param) throws Exception {
        mongoBaseDao.delete(param, MongoTable.good);
    }

    @Override
    public DBObject getGood(Map param) throws Exception {
        return (DBObject) mongoBaseDao.findOne(param, DBObject.class, MongoTable.good);
    }

    @Override
    public List getListFromSolr(Map param, Integer pageSize, Integer pageNum, Map<String, SolrQuery.ORDER> orderMap) throws Exception {
        return SolrBaseDao.queryFromeSolrByPage(MongoTable.good, param, null, null, pageSize, (pageNum - 1) * pageSize, orderMap);
    }

    @Override
    public List<DBObject> getShopGoodList(Map params, DBObject sort) throws Exception {
        return (List<DBObject>) mongoBaseDao.getPageList(params, DBObject.class, 1, 10, MongoTable.good, sort);
    }

    @Override
    public Map goodComment(Map params, NeiyiUser user) throws Exception {

        if (CommonUtils.isEmpty(params.get("order_id"))) {
            throw new BizException("订单id不能为空");
        }
        String orderId = String.valueOf(params.get("order_id"));
        OrderGood orderGood = orderService.getOrderById(orderId);
        if (CommonUtils.isEmpty(orderGood)) {
            throw new BizException("订单信息不存在");
        }
        if (!orderGood.getStatus().equals(OrderEnum.RECED_CONFIRMATION)) {
            throw new BizException("您还未收货，无法评价订单哦！");
        }
        params.put("good_id", orderGood.getGoodId());
        params.put("nickname", user.getUserType()==0?user.getName():user.getCompanyName());

        Map<String, Object> query = new HashedMap();
        query.put("good_id", params.get("good_id"));
        query.put("user_id", user.getId());
        query.put("order_id", params.get("order_id"));
        Long count = mongoBaseDao.count(query, MongoTable.good_comment);
        if (count > 0) {
            throw new BizException("已评论过该订单");
        }

        if (CommonUtils.isEmpty(params.get("content"))) {
            throw new BizException("评论内容不能为空");
        }
        if (CommonUtils.isEmpty(params.get("level"))) {
            throw new BizException("评论类型不能为空");
        }
        params.put("user_id", user.getId());
        params.put("user_logo", user.getUserLogo());
        params.put("comment_time", new Timestamp(System.currentTimeMillis()));
        mongoBaseDao.insert(params, MongoTable.good_comment);
        return params;
    }

    @Override
    public DBObject getOrderComment(String orderId, String wxUserId) throws Exception {
        Map query = new HashMap();
        query.put("order_id", orderId);
        query.put("user_id", wxUserId);

        return (DBObject) mongoBaseDao.findOne(query, DBObject.class, MongoTable.good_comment);
    }

    @Override
    public List<DBObject> getGoodCommentListForPage(Map params, Integer pageSize, Integer pageNum) throws Exception {
        DBObject sort = new BasicDBObject("comment_time", Sort.Direction.DESC.toString());
        List<DBObject> list = (List<DBObject>) mongoBaseDao.getPageList(params, DBObject.class, pageSize, pageNum, MongoTable.good_comment, sort);
        for (DBObject comment : list) {
            List<String> imgs = (List<String>) comment.get("pics");
            if (CollectionUtils.isNotEmpty(imgs)) {
                List<String> notEmptyImg = new ArrayList<>();
                for (String img : imgs) {
                    if (StringUtils.isNotEmpty(img)) {
                        notEmptyImg.add(img);
                    }
                }
                comment.put("pics", notEmptyImg);
            }
        }
        return list;
    }

    @Override
    public Map<String, Long> facetCommentLevel(String good_id) throws Exception {
        MCondition mc = MCondition.create(MRel.and).append("level", 1).append("good_id", good_id);
        MCondition mc1 = MCondition.create(MRel.and).append("level", 2).append("good_id", good_id);
        MCondition mc2 = MCondition.create(MRel.and).append("level", 3).append("good_id", good_id);

        MCondition allMc = MCondition.create(MRel.and).append("good_id", good_id);


        long count = mongoBaseDao.count(mc.toDBObject().toMap(), MongoTable.good_comment);
        long count1 = mongoBaseDao.count(mc1.toDBObject().toMap(), MongoTable.good_comment);
        long count2 = mongoBaseDao.count(mc2.toDBObject().toMap(), MongoTable.good_comment);
        long countAll = mongoBaseDao.count(allMc.toDBObject().toMap(), MongoTable.good_comment);

        Map<String, Long> levelCount = new HashMap<>();
        levelCount.put("好评", count);
        levelCount.put("一般", count1);
        levelCount.put("差评", count2);
        levelCount.put("全部", countAll);

        return levelCount;
    }

    @Override
    public void addGoodSales(String goodId) throws Exception {

        Map<String, Object> query = new HashedMap();
        query.put("good_id", goodId);
        DBObject good = (DBObject) mongoBaseDao.findOne(query, DBObject.class, MongoTable.good);

        Integer salesAmount = 0;
        if (good.containsField("sale_amount")) {
            salesAmount = Integer.parseInt(good.get("sale_amount").toString());
        }

        salesAmount++;
        good.put("sale_amount", salesAmount);

        mongoBaseDao.updateOne(query, good.toMap(), MongoTable.good);
    }

    @Override
    public List<DBObject> getNewGoodSet(String city, CarouselType type) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("city", city);
        if (type != null) {
            params.put("link_type", type.toString());
        }
        List<DBObject> infolist = (List<DBObject>) mongoBaseDao.getList(params, DBObject.class, MongoTable.portal_newgood);
        return infolist;
    }

    @Override
    public int
    updateNewGoodSet(Map param, Map updateItem) throws Exception {
        int cont = mongoBaseDao.updateOne(param, updateItem, MongoTable.portal_newgood);
        return cont;
    }

    @Override
    public void goodCollect(String goodId, boolean flag) throws Exception {
          Map goodParam = new HashMap();
          goodParam.put("good_id",goodId);
          DBObject good =getGood(goodParam);
        if (good == null) {
            throw new BizException("要收藏的商品不存在!");
        }
        Map param = new HashMap();
        param.put("user_id", CurrentRequest.getCurrentUserId().toString());
        param.put("type", CollectTypeEnum.GOOD);
        param.put("id", goodId);
        Object url = Array.get(good.get("img"), 0);

        param.put("head_img", url.toString());
        param.put("name", good.get("goodName"));
        DBObject collect = (DBObject) mongoBaseDao.findOne(param, DBObject.class, MongoTable.collection);
        Map query = new HashMap();
        query.put("good_id", goodId);
        Map update = new HashMap();

        if (collect == null && flag) {
            mongoBaseDao.insert(param, MongoTable.collection);
            good.put("collect_count",good.get("collect_count")== null ? 1 : (Integer)good.get("collect_count") + 1);
            update.put("collect_count", good.get("collect_count"));
            updateNewGoodSet(query, update);
        } else if (collect != null && !flag) {
            mongoBaseDao.delete(param, MongoTable.collection);
            good.put("collect_count",good.get("collect_count")== null ? 0 : (Integer)good.get("collect_count") -1);
            update.put("collect_count", good.get("collect_count"));
           updateNewGoodSet(query, update);
        }
    }


}
